package com.knowledgeqa.system.controller;

import com.knowledgeqa.system.entity.Question;
import com.knowledgeqa.system.service.QuestionService;
import com.knowledgeqa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 添加User类的导入
import com.knowledgeqa.system.entity.User;

/**
 * 问题控制器
 */
@RestController
@RequestMapping("/api/question")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private UserService userService;

    /**
     * 热门问题接口 - 支持指定数量
     */
    @GetMapping("/featured")
    public ResponseEntity<Map<String, Object>> getFeaturedQuestions(@RequestParam(defaultValue = "5") Integer limit) {
        Map<String, Object> result = new HashMap<>();
        List<Question> questions = questionService.findTopRewardedQuestions(limit);

        // 构建前端需要的问题信息列表，包含用户名
        List<Map<String, Object>> questionList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> questionInfo = new HashMap<>();

            // 复制原始问题的所有属性
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("rewardAmount", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            questionInfo.put("viewCount", question.getViewCount());
            questionInfo.put("answerCount", question.getAnswerCount());
            questionInfo.put("userId", question.getUserId());
            questionInfo.put("content", question.getContent());
            questionInfo.put("status", question.getStatus());

            // 获取提问者昵称或用户名
            try {
                User user = userService.findById(question.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        questionInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        questionInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        questionInfo.put("username", "用户" + question.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    questionInfo.put("username", "用户" + question.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                questionInfo.put("username", "用户" + question.getUserId());
            }

            questionList.add(questionInfo);
        }

        result.put("success", true);
        result.put("questions", questionList);
        return ResponseEntity.ok(result);
    }

    /**
     * 热门问题接口 - 悬赏金额排行
     */
    @GetMapping("/rewarded-top3")
    public ResponseEntity<Map<String, Object>> getTop3RewardedQuestions() {
        Map<String, Object> result = new HashMap<>();
        List<Question> questions = questionService.findTop3RewardedQuestions();

        // 构建前端需要的问题信息列表，包含用户名
        List<Map<String, Object>> questionList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> questionInfo = new HashMap<>();

            // 复制原始问题的所有属性
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("rewardAmount", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            questionInfo.put("viewCount", question.getViewCount());
            questionInfo.put("answerCount", question.getAnswerCount());
            questionInfo.put("userId", question.getUserId());
            questionInfo.put("content", question.getContent());
            questionInfo.put("status", question.getStatus());

            // 获取提问者昵称或用户名
            try {
                User user = userService.findById(question.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        questionInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        questionInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        questionInfo.put("username", "用户" + question.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    questionInfo.put("username", "用户" + question.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                questionInfo.put("username", "用户" + question.getUserId());
            }

            questionList.add(questionInfo);
        }

        result.put("success", true);
        result.put("questions", questionList);
        return ResponseEntity.ok(result);
    }

    /**
     * 热门问题接口 - 浏览量排行（支持指定数量）
     */
    @GetMapping("/viewed-top")
    public ResponseEntity<Map<String, Object>> getTopViewedQuestions(@RequestParam(defaultValue = "5") Integer limit) {
        Map<String, Object> result = new HashMap<>();
        List<Question> questions = questionService.findTopViewedQuestions(limit);

        // 构建前端需要的问题信息列表，包含用户名
        List<Map<String, Object>> questionList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> questionInfo = new HashMap<>();

            // 复制原始问题的所有属性
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("rewardAmount", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            questionInfo.put("viewCount", question.getViewCount());
            questionInfo.put("answerCount", question.getAnswerCount());
            questionInfo.put("userId", question.getUserId());
            questionInfo.put("content", question.getContent());
            questionInfo.put("status", question.getStatus());

            // 获取提问者昵称或用户名
            try {
                User user = userService.findById(question.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        questionInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        questionInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        questionInfo.put("username", "用户" + question.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    questionInfo.put("username", "用户" + question.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                questionInfo.put("username", "用户" + question.getUserId());
            }

            questionList.add(questionInfo);
        }

        result.put("success", true);
        result.put("questions", questionList);
        return ResponseEntity.ok(result);
    }

    /**
     * 热门问题接口 - 浏览量排行（前三个）
     */
    @GetMapping("/viewed-top3")
    public ResponseEntity<Map<String, Object>> getTop3ViewedQuestions() {
        Map<String, Object> result = new HashMap<>();
        List<Question> questions = questionService.findTop3ViewedQuestions();

        // 构建前端需要的问题信息列表，包含用户名
        List<Map<String, Object>> questionList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> questionInfo = new HashMap<>();

            // 复制原始问题的所有属性
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("rewardAmount", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            questionInfo.put("viewCount", question.getViewCount());
            questionInfo.put("answerCount", question.getAnswerCount());
            questionInfo.put("userId", question.getUserId());
            questionInfo.put("content", question.getContent());
            questionInfo.put("status", question.getStatus());

            // 获取提问者昵称或用户名
            try {
                User user = userService.findById(question.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        questionInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        questionInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        questionInfo.put("username", "用户" + question.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    questionInfo.put("username", "用户" + question.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                questionInfo.put("username", "用户" + question.getUserId());
            }

            questionList.add(questionInfo);
        }

        result.put("success", true);
        result.put("questions", questionList);
        return ResponseEntity.ok(result);
    }

    /**
     * 发布悬赏问题
     */
    @PostMapping("/publish")
    public ResponseEntity<Map<String, Object>> publishQuestion(@RequestBody Question question) {
        Map<String, Object> result = new HashMap<>();

        // 检查用户金币余额是否足够
        Integer coinBalance = userService.getCoinBalance(question.getUserId());
        if (coinBalance < question.getRewardAmount()) {
            result.put("success", false);
            result.put("message", "金币余额不足");
            return ResponseEntity.ok(result);
        }

        // 发布问题
        boolean success = questionService.publishQuestion(question);
        if (success) {
            // 扣除用户金币
            userService.consumeCoin(question.getUserId(), question.getRewardAmount(), 1, "发布悬赏问题：" + question.getTitle());
            result.put("success", true);
            result.put("message", "问题发布成功");
        } else {
            result.put("success", false);
            result.put("message", "问题发布失败");
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 查询用户发布的问题
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserQuestions(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        List<Question> questions = questionService.findByUserId(userId);

        // 构建前端需要的问题信息列表，包含用户名
        List<Map<String, Object>> questionList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> questionInfo = new HashMap<>();

            // 复制原始问题的所有属性
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("rewardAmount", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            questionInfo.put("viewCount", question.getViewCount());
            questionInfo.put("answerCount", question.getAnswerCount());
            questionInfo.put("userId", question.getUserId());
            questionInfo.put("content", question.getContent());
            questionInfo.put("status", question.getStatus());

            // 获取提问者昵称或用户名
            try {
                User user = userService.findById(question.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        questionInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        questionInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        questionInfo.put("username", "用户" + question.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    questionInfo.put("username", "用户" + question.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                questionInfo.put("username", "用户" + question.getUserId());
            }

            questionList.add(questionInfo);
        }

        result.put("success", true);
        result.put("questions", questionList);
        return ResponseEntity.ok(result);
    }

    /**
     * 分页查询问题列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getQuestionList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {

        Map<String, Object> params = new HashMap<>();
        params.put("start", (page - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("keyword", keyword);
        params.put("status", status);

        Map<String, Object> result = new HashMap<>();
        List<Question> questions = questionService.findPage(params);
        int total = questionService.findCount(params);

        // 构建前端需要的问题信息列表，包含用户名
        List<Map<String, Object>> questionList = new ArrayList<>();
        for (Question question : questions) {
            Map<String, Object> questionInfo = new HashMap<>();

            // 复制原始问题的所有属性
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("rewardAmount", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            questionInfo.put("viewCount", question.getViewCount());
            questionInfo.put("answerCount", question.getAnswerCount());
            questionInfo.put("userId", question.getUserId());
            questionInfo.put("content", question.getContent());
            questionInfo.put("status", question.getStatus());

            // 获取提问者昵称或用户名
            try {
                User user = userService.findById(question.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        questionInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        questionInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        questionInfo.put("username", "用户" + question.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    questionInfo.put("username", "用户" + question.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                questionInfo.put("username", "用户" + question.getUserId());
            }

            questionList.add(questionInfo);
        }

        result.put("success", true);
        result.put("questions", questionList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return ResponseEntity.ok(result);
    }

    /**
     * 获取问题详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getQuestionDetail(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        Question question = questionService.findById(id);
        if (question != null) {
            // 构建前端需要的问题信息，包含用户名
            Map<String, Object> questionInfo = new HashMap<>();

            // 复制原始问题的所有属性
            questionInfo.put("id", question.getId());
            questionInfo.put("title", question.getTitle());
            questionInfo.put("content", question.getContent());
            questionInfo.put("rewardAmount", question.getRewardAmount());
            questionInfo.put("createTime", question.getCreateTime());
            questionInfo.put("viewCount", question.getViewCount());
            questionInfo.put("answerCount", question.getAnswerCount());
            questionInfo.put("userId", question.getUserId());
            questionInfo.put("status", question.getStatus());

            // 获取提问者昵称或用户名
            try {
                User user = userService.findById(question.getUserId());
                if (user != null) {
                    // 优先显示昵称
                    if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                        questionInfo.put("username", user.getNickname());
                    } else if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                        // 其次显示用户名
                        questionInfo.put("username", user.getUsername());
                    } else {
                        // 都没有则显示"用户+用户id"
                        questionInfo.put("username", "用户" + question.getUserId());
                    }
                } else {
                    // 用户不存在则显示"用户+用户id"
                    questionInfo.put("username", "用户" + question.getUserId());
                }
            } catch (Exception e) {
                // 如果获取失败，显示"用户+用户id"
                questionInfo.put("username", "用户" + question.getUserId());
            }

            result.put("success", true);
            result.put("question", questionInfo);
        } else {
            result.put("success", false);
            result.put("message", "问题不存在");
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 删除问题
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteQuestion(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        boolean success = questionService.deleteById(id);
        result.put("success", success);
        result.put("message", success ? "问题删除成功" : "问题删除失败");
        return ResponseEntity.ok(result);
    }

    /**
     * 关闭问题
     */
    @PutMapping("/close/{id}")
    public ResponseEntity<Map<String, Object>> closeQuestion(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        boolean success = questionService.closeQuestion(id);
        result.put("success", success);
        result.put("message", success ? "问题已关闭" : "操作失败");
        return ResponseEntity.ok(result);
    }

    /**
     * 采纳最佳答案
     */
    @PutMapping("/accept-answer")
    public ResponseEntity<Map<String, Object>> acceptAnswer(@RequestBody Map<String, Object> acceptInfo) {
        Long questionId = Long.valueOf(acceptInfo.get("questionId").toString());
        Long answerId = Long.valueOf(acceptInfo.get("answerId").toString());

        Map<String, Object> result = new HashMap<>();
        boolean success = questionService.acceptAnswer(questionId, answerId);
        result.put("success", success);
        result.put("message", success ? "已采纳最佳答案" : "操作失败");
        return ResponseEntity.ok(result);
    }
}